package com.example.app7;

import androidx.appcompat.app.AppCompatActivity;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.app7.adapter.ImageAdapter;
import com.google.android.material.snackbar.Snackbar;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    // 广播中的对象列表数据
    private List<MyData> userList=new ArrayList<>();
    // 通过service绑定的对象列表数据，这里没有用到，用的是广播来获取数据
    List<MyData> myData=new ArrayList<>();

    //service对象
    IRemoteService iRemoteService;
    //集合布局
    private RecyclerView relist;

    //广播接收器
    private BroadcastReceiver receiver;

    //Snakebar 提示布局
    private CoordinatorLayout cl_main;

    //用于判断服务端与客户端是否连接成功
    private boolean mIsAidlConnected = false;

    //此状态可以判断是否要关闭service  true为关闭
    private boolean status;

    private Intent it1;

    //最后一个数据是索引
    private int lastPosition;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //集合组件
        relist = findViewById(R.id.relist);

        //Snakebar 提示信息布局组件
        cl_main = findViewById(R.id.cl_main);


        it1 = new Intent();
        it1.setAction("com.test.remote.action");
        it1.setPackage("com.example.app7");
        //绑定service
        bindService(it1, serviceConnection, Context.BIND_AUTO_CREATE);
        //启动seivice
        startService(it1);


        // 注册广播接收器
        receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(RemoteService.ACTION_UPDATE_DATA)) {
                    //此状态可以判断是否要关闭service
                    status = intent.getBooleanExtra("status", false);
                    //更新了多少条数据
                    int shuliang = intent.getIntExtra("shuliang", 0);
                    //更新了多少次
                    int record = intent.getIntExtra("record", 0);

                    //要是为true则关闭service，注意要先解绑，最后再销毁
                    if (status) {
                        //提示信息
                        Snackbar snackbar1 =   Snackbar.make(cl_main, "以断开连接", Snackbar.LENGTH_LONG);
                        //按钮
                        snackbar1.setAction("Go to last", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                MyData myData1 = userList.get(lastPosition);
                                Toast.makeText(getApplicationContext(), "最后一条数据为"+myData1.getName(),Toast.LENGTH_SHORT).show();
                            }
                        });
                        //显示
                        snackbar1.show();

                        //解除service绑定
                        unbindService(serviceConnection);
                        //销毁service
                        stopService(it1);
                    } else {

                        // 获取广播中的对象列表数据
                        userList = intent.getParcelableArrayListExtra(RemoteService.EXTRA_DATA);
                        //提示信息
                        Snackbar snackbar =  Snackbar.make(cl_main,"第"+record+"次更新了"+shuliang+"条数据",Snackbar.LENGTH_LONG);
                        //按钮
                        snackbar.setAction("Go to last", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                MyData myData1 = userList.get(lastPosition);
                                Toast.makeText(getApplicationContext(), "最后一条数据为"+myData1.getName(),Toast.LENGTH_SHORT).show();
                            }
                        });
                        //显示信息
                        snackbar.show();

                        //下面是把service通过广播传过来的数据进行封装展示
                        relist.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
                        ImageAdapter imageAdapter = new ImageAdapter(getApplicationContext(), userList);
                        //获取最后一个数据的索引
                        lastPosition =  imageAdapter.getItemCount() - 1;
                        relist.setAdapter(imageAdapter);

                        // 更新数据后跳转到最后一行
                        relist.scrollToPosition(lastPosition);
                    }

                }
            }
        };
        //创建一个广播拦截器
        IntentFilter filter = new IntentFilter();
        //接收的暗号
        filter.addAction(RemoteService.ACTION_UPDATE_DATA);
        //进行广播注册
        registerReceiver(receiver, filter);



    }


    /**
     * 获取返回的数据
     */
     ServiceConnection serviceConnection  =new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d(RemoteService.TAG, "onServiceConnected: ");

            // 这里表示与服务端成功建立连接
            mIsAidlConnected = true;


            Snackbar.make(cl_main,"连接成功",Snackbar.LENGTH_LONG).show();

            iRemoteService = IRemoteService.Stub.asInterface(iBinder);

            //下面的数据没什么用，在这里用的是广播传的数据，写在这里是方便下次知道是如何接收数据
                        try {
                            int pid = iRemoteService.getPid();
                            myData = iRemoteService.getMyData();
                        } catch (RemoteException e) {
                            throw new RuntimeException(e);
                        }

               Log.d("xxf123", "我零零: "+userList);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d(RemoteService.TAG, "onServiceDisconnected: ");
            iRemoteService = null;
        }
    };


}